package com.lin.utils;

import com.lin.controller.LoginController;
import com.lin.pojo.User;
import com.lin.realm.MyShiroRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

import java.util.Map;

/**
 * Shiro工具类
 */
public class ShiroUtil {

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static User getUser() {
        return (User) SecurityUtils.getSubject().getPrincipal();
    }

    public static Integer getUserId() {
        return getUser().getId();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }


    //验证码
    public static String getKaptcha(String key) {
        String kaptcha = getSessionAttribute(key).toString();
        getSession().removeAttribute(key);
        return kaptcha;
    }

    /**
     * testing
     */
    public static void reloadAuthorizing(MyShiroRealm realm, String username) {
        Subject subject = SecurityUtils.getSubject();
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        SimplePrincipalCollection principals = new SimplePrincipalCollection(username, realmName);
        subject.runAs(principals);
        SecurityUtils.getSubject().logout();
        PrincipalCollection principals1 = subject.getPrincipals();
        Object principal = subject.getPrincipal();
        realm.getAuthorizationCache().remove(subject.getPrincipal());
        subject.releaseRunAs();
    }

    /**
     * 清除指定用户权限信息（可用）
     * 虽然传的是用户名，但是缓存实际key还是User对象
     */
    public static void clearUserAuthorizationInfo(String username) throws Exception {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        Cache<Object, AuthorizationInfo> cache = realm.getAuthorizationCache();
        assert cache != null;
        for (Object key : cache.keys()) {
            Map<String, String> map = StringToObject.getMap("[" + key + "]");
            User user = StringToObject.getObject(map, User.class);
            String accountNumber = user.getAccountNumber();
            if (username.equals(accountNumber))
                cache.remove(key);
        }
    }

    /**
     * 清除指定用户登录信息（可用）
     * 此处key为username,不知道为什么
     */
    public static void clearUserAuthenticationInfo(String username) throws Exception {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        Cache<Object, AuthenticationInfo> cache = realm.getAuthenticationCache();
        assert cache != null;
        for (Object key : cache.keys()) {
            if (username.equals(key + ""))
                cache.remove(key);
        }
    }


    /**
     * 清除所有用户授权信息缓存.(可用)
     */
    public static void clearAllCachedInfo() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        Cache<Object, AuthorizationInfo> cache = realm.getAuthorizationCache();
        Cache<Object, AuthenticationInfo> cache1 = realm.getAuthenticationCache();
        if (cache1 != null) {
            for (Object key : cache1.keys()) {
                cache1.remove(key);
            }
        }
        if (cache != null) {
            for (Object key : cache.keys()) {
                cache.remove(key);
            }
        }
    }

    /**
     * 清除指定用户所有缓存.(可用)
     */
    public static void clearAllCachedInfo(String username) throws Exception {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        Cache<Object, AuthorizationInfo> cache = realm.getAuthorizationCache();
        Cache<Object, AuthenticationInfo> cache1 = realm.getAuthenticationCache();
//        登录信息
        if (cache1 != null) {
            for (Object key : cache1.keys()) {
                if (username.equals(key + ""))
                    cache1.remove(key);
            }
        }
//        权限信息
        if (cache != null) {
            for (Object key : cache.keys()) {
                User user = StringToObject.getObject(StringToObject.getMap("[" + key + "]"), User.class);
                String accountNumber = user.getAccountNumber();
                if (username.equals(accountNumber))
                    cache.remove(key);
            }

        }
    }
}
